<template>
  <!--  配置版本管理-->
  <div class="page">
    <!-- 条件筛选 -->
    <div class="page_filter">
      <el-input v-model="form.queryString" clearable placeholder="姓名/电话/公司/职位/部门...">
        <template slot="prepend">查询条件</template>
      </el-input>
      <el-button class="common_btn-defalut" icon="el-icon-search" @click="form.page=1;queryList()">搜索</el-button>
    </div>
    <div class="page_main">
      <el-button icon="el-icon-plus" slot="reference" class="common_btn-small" @click="addCustomer">新增客户</el-button>
      <!-- table -->
      <div class="common_btnBox">
        <i class="iconfont iconzongshu icon-size"></i>
        总数：{{form.total}}
      </div>
      <el-table :data="tableList" border>
        <el-table-column label="序号" fixed width="80">
          <template slot-scope="scope">
            {{getIndex(scope.$index)}}
          </template>
        </el-table-column>
        <el-table-column type="expand" fixed label="详情信息" width="95px">
          <template slot-scope="scope">
            <el-button type="primary" size="small" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑客户信息</el-button>
            <el-form label-position="left" label-suffix="：" class="demo-table-expand">
              <el-form-item label="重要程度">
                <el-rate v-model="scope.row.importance"
                         disabled
                         show-text
                         text-color="#2196f3"
                         :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                         :texts="['普通','一般','关注','重要','很重要']"></el-rate>
              </el-form-item>
              <el-form-item label="生日">
                <span>{{ scope.row.birthday | formatTimer2 }}</span>
              </el-form-item>
              <el-form-item label="籍贯">
                <span>{{ scope.row.area?scope.row.area:'---' }}</span>
              </el-form-item>
              <el-form-item label="住址">
                <span>{{ scope.row.address?scope.row.address:'---'}}</span>
              </el-form-item>
              <el-form-item label="毕业院校">
                <span>{{ scope.row.school?scope.row.school:'---' }}</span>
              </el-form-item>
              <el-form-item label="邮箱">
                <span>{{ scope.row.email?scope.row.email:'---' }}</span>
              </el-form-item>
              <el-form-item label="微信">
                <span>{{ scope.row.weixin?scope.row.weixin:'---' }}</span>
              </el-form-item>
              <el-form-item label="感兴趣的产品">
                <el-tag size="mini" effect="dark" style="margin-left: 5px" v-for="tag in scope.row.tagList"
                        :key="tag.id">
                  {{tag.name}}<span v-if="tag.price">({{'￥'+tag.price}})</span>
                </el-tag>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="visitStatusName" label="拜访状态" width="100">
          <template slot-scope="scope">
            <el-tag size="mini" :style="scope.row.visitStatus| gradeVisitStatusColor" style="color: white">
              {{scope.row.visitStatusName}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" min-width="90"></el-table-column>
        <el-table-column prop="genderName" label="性别" width="80"></el-table-column>
        <el-table-column prop="phone" label="联系电话" width="125"></el-table-column>
        <el-table-column prop="companyName" label="公司" show-overflow-tooltip min-width="220"></el-table-column>
        <el-table-column prop="dept" label="部门" width="100"></el-table-column>
        <el-table-column prop="duties" label="职位" width="100"></el-table-column>
        <el-table-column prop="orderCount" label="订单总数" width="100"></el-table-column>
        <el-table-column prop="visitCount" label="拜访总数" width="100"></el-table-column>
        <el-table-column prop="salesVolume" label="销售总额" width="120"></el-table-column>
        <el-table-column prop="receivableVolume" label="应收账款" width="120"></el-table-column>
        <el-table-column label="操作" fixed="right" width="230">
          <template slot-scope="scope">
            <button class="btn_edit" @click="visitAdd(scope.row)">新增拜访</button>
            <button class="btn_add">销售记录</button>
            <button class="btn_add" @click="handleEdit(scope.row)">拜访记录</button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="form.page"
                     :page-size="form.pageSize"    :page-sizes="[10, 20, 30, 40,50,60,70,80,90,100]"
                     layout="sizes, prev, pager, next" :total="form.total">
      </el-pagination>
      <!--  新增客户-->
      <el-drawer
        :title="dialogTitle"
        :visible.sync="isShowAddDialog"
        direction="rtl"
        custom-class="demo-drawer"
        ref="drawer"
        size="50%">
        <div class="demo-drawer__content">
          <!-- 具体form表单 -->
          <el-form label-position="right" ref="customer" label-suffix="：" :rules="rule" :model="customer"
                   label-width="0px">
            <el-divider content-position="left">基本信息</el-divider>
            <el-form-item prop="companyId" label-width="100px" label="重要程度">
              <el-rate v-model="customer.importance"
                       show-text
                       text-color="#2196f3"
                       :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                       :texts="['普通','一般','关注','重要','很重要']"></el-rate>
            </el-form-item>
            <div>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item prop="name">
                    <el-input v-model="customer.name" placeholder="请输入">
                      <template slot="prepend">姓名</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="birthday">
                    <el-date-picker
                      v-model="customer.birthday"
                      type="date"
                      style="width: 100%;"
                      placeholder="选择生日">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item prop="areaId">
                    <region-unit v-model="customer.areaId" :key="customer.areaId"
                                 :placeholder="'请选择客户籍贯'"></region-unit>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item prop="phone">
                    <el-input v-model="customer.phone" show-word-limit  clearable type="text" :maxlength="11" placeholder="请输入">
                      <template slot="prepend">联系电话</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="email">
                    <el-input v-model="customer.email" clearable placeholder="请输入">
                      <template slot="prepend">邮箱</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="address">
                    <el-input v-model="customer.address" clearable placeholder="请输入">
                      <template slot="prepend">住址</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">

                  <el-form-item prop="gender">
                    <el-radio-group v-model="customer.gender">
                      <el-radio-button v-for="item in EnumGenderList" :key="item.code" :label="item.code">{{item.name}}
                      </el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item prop="weixin">
                    <el-input v-model="customer.weixin" clearable placeholder="请输入">
                      <template slot="prepend">微信</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="school">
                    <el-input v-model="customer.school" clearable placeholder="请输入">
                      <template slot="prepend">毕业院校</template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <el-divider content-position="left">单位信息</el-divider>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item prop="companyId">
                  <el-select v-model="customer.companyId"  style="width: 90%"  clearable filterable placeholder="请选择公司">
                    <el-option
                      v-for="item in companyList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                  <i class="el-icon-refresh icon-size" style="cursor: pointer;" @click="removeAllCompanyStorage"></i>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="dept">
                  <el-input v-model="customer.dept" clearable placeholder="请输入">
                    <template slot="prepend">部门</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="duties">
                  <el-input v-model="customer.duties" clearable placeholder="请输入">
                    <template slot="prepend">职位</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider content-position="left">感兴趣的产品</el-divider>
            <el-select v-model="customer.tagIdList" multiple filterable placeholder="请选择客户感兴趣的产品(支持多选)" >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name + '(￥' +item.price+')'"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form>
        </div>
        <div class="demo-drawer__footer">
          <el-button @click="isShowAddDialog=false" type="info">取 消</el-button>
          <el-button type="primary" class=" common_btn-defalut" @click="validateAddForm">确 定</el-button>
        </div>
      </el-drawer>
      <!--  新增拜访-->
      <el-dialog title="新增拜访" :visible.sync="isShowVisitDialog" :close-on-click-modal="false" width="600px">
        <el-form label-position="right" ref="visit" label-suffix="：" :rules="visitRule" :model="visit"
                 label-width="0px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item prop="customerName">
                <el-input v-model="visit.customName" size="mini" disabled>
                  <template slot="prepend">客户姓名</template>
                </el-input>
              </el-form-item>
              <el-form-item prop="dept">
                <el-input v-model="visit.dept" size="mini" disabled>
                  <template slot="prepend">所在部门</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="companyName">
                <el-input v-model="visit.companyName" size="mini" disabled>
                  <template slot="prepend">所在单位</template>
                </el-input>
              </el-form-item>
              <el-form-item prop="duties">
                <el-input v-model="visit.duties" size="mini" disabled>
                  <template slot="prepend">担任职位</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item prop="visitTime" label="拜访时间" label-width="100px">
            <el-date-picker
              v-model="visit.visitTime"
              type="date"
              style="width: 100%;"
              placeholder="选择拜访日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item prop="visitAddress" label="拜访地点" label-width="100px">
            <el-input v-model="visit.visitAddress" clearable placeholder="请输入">
            </el-input>
          </el-form-item>
          <el-form-item prop="product" label="演示产品" label-width="100px">
            <el-select v-model="visit.product" multiple filterable placeholder="请选择演示产品(支持多选)" @change="changeProduct">
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name + '(￥' +item.price+')'"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="productVolume" label="产品总价" label-width="100px">
            <el-input v-model="visit.productVolume" disabled placeholder="自动计算">
            </el-input>
          </el-form-item>
        </el-form>
        <!-- 操作按钮 -->
        <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="isShowVisitDialog = false">取消</el-button>
        <el-button class="common_btn-defalut" type="primary" @click="validateVisitForm">确定</el-button>
      </span>
      </el-dialog>
    </div>
    <x-loading v-show="isLoading"></x-loading>
  </div>
</template>
<script>
import {
  getCustomerList,
  addCustomer,
  updateCustomer,
  getProductSelectList,
  addVisit
} from '@/services/ERP/sale'
import RegionUnit from '@/components/region-unit'
import ItemMixins from "../item.mixins";
import XLoading from '@/components/animation/x-loading.vue'
import Enums from '@/utils/enums'

// form表单校验规则
export default {
  components: {XLoading, RegionUnit},
  mixins: [ItemMixins,Enums],
  data() {
    return {
      form: {
        page: 1,
        pageSize: 10,
        companyType: 2,
        total: 0,
      },
      rule: {
        name: {required: true, message: '请输入客户名称'},
        phone: {required: true, message: '请输入客户电话'},
      },
      visitRule: {
        visitTime: {required: true, message: '请选择拜访时间'},
        visitAddress: {required: true, message: '请输入拜访地点'},
      },
      customer: {
        tagIdList:[]
      },
      visit: {},
      tableList: [],
      productList: [],
      EnumGenderList: [],
      isShowAddDialog: false,
      isShowVisitDialog: false,
      isLoading: false,
      tagList: []
    }
  },
  computed: {
    // 弹窗的title
    dialogTitle() {
      return this.customer.id ? '编辑客户信息' : '新增客户信息'
    },
    companyList(){
      return this.allCompanyList.filter(x => x.type !== 1)
    },
  },
  methods: {
    /////////////////////////////////////////////拜访开始
    // 获取演示产品选项
    async getProductSelectList() {
      let res = await getProductSelectList()
      this.productList = res.data || []
    },
    //选择演示产品计算总额
    changeProduct() {
      let list = this.productList.filter(x => this.visit.product.indexOf(x.id) !== -1)
      let money = 0
      list.map(x => {
        money += x.price
      })
      this.visit.productVolume = money
    },
    visitAdd(row) {
      this.visit = {
        product: [],
        customId: row.id,
        productVolume: 0,
        customName: row.name,
        customPhone: row.phone,
        companyName: row.companyName ? row.companyName : '---',
        dept: row.dept ? row.dept : '---',
        duties: row.duties ? row.duties : '---',
      }
      this.isShowVisitDialog = true
    },
    // 表单提交
    validateVisitForm() {
      this.$refs.visit.validate((valid) => {
        if (valid) {
          this.submitVisit()
        }
      })
    },
    async submitVisit() {
      let res = await addVisit(this.visit)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: '添加成功！'
        })
        this.isShowVisitDialog = false
        this.queryList()
      }
    },
    /////////////////////////////////////////////拜访结束
    // 表单提交
    validateAddForm() {
      this.$refs.customer.validate((valid) => {
        if (valid) {
          this.submitCustomer()
        }
      })
    },
    async submitCustomer() {
      let action = this.customer.id ? updateCustomer : addCustomer
      let res = await action(this.customer)
      if (res.code === 200) {
        this.$notify({
          type: 'success',
          title: '提示',
          message: this.customer.id ? '更新成功！' : '添加成功！'
        })
        this.isShowAddDialog = false
        this.queryList()
      }
    },
    // 获取当前的序号
    getIndex(index) {
      let param = (this.form.page - 1) * this.form.pageSize + index + 1
      return param
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.form.pageSize = val
      this.queryList()
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.form.page = val
      this.queryList()
    },
    async queryList() {
      this.isLoading = true
      let res = await getCustomerList(this.form)
      this.tableList = res.data?.records || []
      this.form.page = Number(res.data?.current)
      this.form.total = Number(res.data?.total)
      this.isLoading = false
    },
    addCustomer() {
      this.isShowAddDialog = true
      this.customer = {
        gender: 1,
        importance: 1,
        tagIdList:[]
      }
      this.$nextTick(() => {
        this.$refs.customer.clearValidate()
      })
    },
    handleEdit(row) {
      this.isShowAddDialog = true
      this.customer = JSON.parse(JSON.stringify(row))
      this.$nextTick(() => {
        this.$refs.customer.clearValidate()
      })
    },
  },
  mounted() {
    this.queryDictList(['EnumGender'],[ 'EnumGenderList'])
    this.queryList()
  },
  activated() {
    this.getAllCompanyList()
    this.getProductSelectList()
  }

}
</script>

<style lang="less" scoped>
  /deep/ .el-tag.el-tag--info {
    background-color: #2196f3;
    border-color: #e9e9eb;
    color: #ffffff;
  }

  .el-divider__text {
    font-size: 20px;
  }

  /deep/ .el-divider--horizontal {
    display: block;
    height: 1px;
    width: 100%;
    margin: 30px 0;
  }

  /deep/ .el-input-group__prepend {
    border-right: 0;
    background: #2196f3;
    color: white;
  }

  /deep/ .el-rate__item {
    font-size: 20px;
    line-height: 40px;
  }

  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }

  /deep/ .el-table__expanded-cell[class*=cell] {
    padding: 20px 90px;
    background: #E3E3E3;
  }
</style>
